// https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <iostream>
#include <vector>

using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};


class Solution {
public:
    vector<vector<int>> res;
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        dfs(root, 0);
        vector<vector<int>> res1;
        for (int i = res.size() - 1; i >= 0; i--) {
            res1.push_back(res[i]);
        }
        return res1;
    }

    void dfs(TreeNode* root, int index) {
        if (root) {
            if (index >= res.size()) res.push_back({});
            res[index].push_back(root->val);
            dfs(root->left, index + 1);
            dfs(root->right, index + 1);
        }        
    }

    TreeNode* init() {
        TreeNode* n1 = new TreeNode(3);
        TreeNode* n2 = new TreeNode(9);
        TreeNode* n3 = new TreeNode(20);
        TreeNode* n4 = new TreeNode(15);
        TreeNode* n5 = new TreeNode(7);
        n1->left = n2;
        n1->right = n3;
        n3->left = n4;
        n3->right = n5;

        return n1;
    }
};

int main() {
    Solution so;
    TreeNode* h1 = so.init();
    auto res = so.levelOrderBottom(h1);
    for (auto items : res) {
        for (auto i : items) {
            cout << i << ",";
        }
        cout << endl;
    }
    return 0;
}